using UnityEngine;
using QFramework;
using System.Linq;
using Unity.VisualScripting;

namespace ProjectSurvivor
{
	public partial class SimleKnife : ViewController//表示一个挂在场景物体上的控制器（如玩家、刷怪器）。
	{
		public BindableProperty<bool> SupperRotateSword = new BindableProperty<bool>(false);

		void Start()
		{
			// Code Here
		}
		private float mCurrentSeconds = 0;
		void Update()
		{
			if(Player.Default)
			{
				mCurrentSeconds += Time.deltaTime;
				if (mCurrentSeconds >=Global.SimpleAbilityDuration.Value )
				{
					mCurrentSeconds = 0; 
					var enemies = FindObjectsByType<Enemy>(FindObjectsInactive.Exclude,FindObjectsSortMode.None).OrderBy(enemy=>Player.Default.Distance2D(enemy)).Take(Global.SimpleSwordCount.Value);
					int i = 0;
					
						if (Global.SimpleSwordCount.Value > 10)
						{
							SupperRotateSword.Value = true;
						}
					foreach (var enemy in enemies)
					{
						if (i < 4)
						{
							ActionKit.DelayFrame(11 * i, () =>
							{
								AudioKit.PlaySound("knife");
							}).StartGlobal();
							i++;
						}

						if (enemy)
						{

							Triangle.Instantiate().Position(this.Position()).Show()
							.Self(self =>
							{
								var selfCache = self;
								self.transform.up = enemy.NormalizedDirection2DFrom(Player.Default);
								var direction = (Vector3)enemy.NormalizedDirection2DFrom(Player.Default);
								var rigidbody2D = self.GetComponent<Rigidbody2D>();
								rigidbody2D.velocity = enemy.NormalizedDirection2DFrom(Player.Default) * 10;
								int attackCount = 0;
								self.OnTriggerEnter2DEvent(collider =>
								{
									var HurtBox = collider.GetComponent<HurtBox>();
									if (HurtBox)
									{
										if (HurtBox.Owner.CompareTag("Enemy"))
										{
											var damageTimes = SupperRotateSword.Value ? Random.Range(2, 3 + 1) : 1;
											if (HurtBox.Owner.GetComponent<Enemy>())
											{
												DamageSystem.CalculateDamage(Global.SimpleAbilityDamage.Value * damageTimes, HurtBox.Owner.GetComponent<Enemy>());
											}
											else
											{
												DamageSystem.CalculateDamage(Global.SimpleAbilityDamage.Value * damageTimes, HurtBox.Owner.GetComponent<EnemyMinBoss>());
											}
											attackCount++;
											if (attackCount >= Global.SimpleSwordCount.Value)
											{
												self.DestroyGameObjGracefully();
											}
										}
									}
								}).UnRegisterWhenGameObjectDestroyed(self);
								ActionKit.OnUpdate.Register(() =>//注册帧更新/UI调试回调；
								{
									if (Player.Default.Distance2D(selfCache) > 20)
									{
										self.DestroyGameObjGracefully();
									}
								}).UnRegisterWhenGameObjectDestroyed(self);

							});
						}
					}
					
				}
			}
			
        }
    }
}
